package com.bw.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.domain.Channel;
import com.bw.domain.ChannelImages;
import com.bw.mapper.ChannelImagesMapper;
import com.bw.service.ChannelImagesService;
import com.bw.service.ChannelService;
import com.bw.mapper.ChannelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
* @author THINKAPD
* @description 针对表【t_channel】的数据库操作Service实现
* @createDate 2024-07-08 15:13:50
*/
@Service
public class ChannelServiceImpl extends ServiceImpl<ChannelMapper, Channel>
    implements ChannelService{

    @Autowired
    ChannelMapper channelMapper;
    @Autowired
    ChannelImagesMapper channelImagesMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public List<Channel> list2() {
        return channelMapper.list2();
    }

    @Transactional
    @Override
    public boolean save2(Channel channel) {

        channel.setCreateTime(new Date());
        channel.setUpdateTime(new Date());
        channel.setStatus("草稿");
        //1.保存栏目表
         this.saveOrUpdate(channel);

         //2.保存到图片表
        List<ChannelImages> channelImages = channel.getChannelImagesList();
        for (ChannelImages channelImage : channelImages) {
            channelImage.setChannelId(channel.getId());
            //存储到数据库
            channelImagesMapper.insert(channelImage);
        }


        return true;
    }

    @Override
    public Channel get(Integer id) {
        return channelMapper.get(id);
    }

    @Override
    public int publish() {
        return channelMapper.publish();
    }

    @Override
    public List<Channel> list3(Channel channel) {
        return channelMapper.list3(channel);
    }

    @Override
    public int updateDBFromRedis() {
        int i=0;
        String  UP_CHANNEL_KEY="UP_CHANNEL_KEY";
        Set<ZSetOperations.TypedTuple> set = redisTemplate.opsForZSet().rangeWithScores(UP_CHANNEL_KEY, 0, Integer.MAX_VALUE);
        for (ZSetOperations.TypedTuple typedTuple : set) {
            Object channelId = typedTuple.getValue();
            Double upNumber = typedTuple.getScore();

          i+=  channelMapper.updateDBFromRedis(channelId,upNumber.intValue());
        }

        return i;
    }

    @Override
    public void updateCommentNum(Integer channelId) {
        channelMapper.updateCommentNum(channelId);
    }
}




